package com.ocpsoft.pretty.time.i18n.impl;

import com.ocpsoft.pretty.time.i18n.I18N;
import com.ocpsoft.pretty.time.i18n.I18NFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * The default {@link com.ocpsoft.pretty.time.i18n.I18NFactory} implementation.
 *
 * @author Mihai CAZACU (cazacugmihai@yahoo.com)
 */
public class DefaultI18NFactory implements I18NFactory {

    public static final String I18N_FILENAME = "prettytime.properties";

    private static class InstanceHolder {
        private static final I18NFactory INSTANCE = new DefaultI18NFactory();
    }

    protected DefaultI18NFactory() {
    }

    /**
     * Returns the instance of this class.
     *
     * @return
     */
    public static final I18NFactory getFactory() {
        return InstanceHolder.INSTANCE;
    }

    @Override
    public I18N getI18N() {
        I18N i18n = null;
        InputStream inputStream = getResource(DefaultI18NFactory.I18N_FILENAME);

        if (inputStream != null) {
            try {
                i18n = new I18NFile(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (i18n == null) {
            i18n = new I18NInMemory();
        }

        return i18n;
    }

    private static InputStream getResource(String resource) {
        try {
            ClassLoader classLoader = DefaultI18NFactory.class.getClassLoader();
            if (classLoader != null) {
                InputStream inputStream = classLoader.getResourceAsStream(resource);
                if (inputStream != null) {
                    return inputStream;
                }
            }
        } catch (Throwable t) {
        }

        return ClassLoader.getSystemResourceAsStream(resource);
    }

}
